import _ from 'lodash';
import fs from 'fs-extra';
import path from 'path';
import ejs from 'ejs';
import { readFileSync } from 'fs';
import { join } from 'path';
import { UserProxy, TopicProxy } from '../proxy';

export default async function (appId, zone) {
  if (!appId) throw new Error('not app id');
  if (!zone) throw new Error('zone is null');

  const conditions = { zoneId: zone._id, good: true };
  const options = { skip: 0, limit: 10, sort: '-top -last_reply_at' };
  const topics = await TopicProxy.find(appId, conditions, options);

  const authorIds = [];
  topics.forEach((item) => {
    if (item.author_id) authorIds.push(item.author_id.toString());
  });

  const authors = await UserProxy.findByIds(appId, authorIds);
  topics.forEach((item) => {
    item.toObject();
    const index = _.findIndex(authors, i => i._id.toString() === item.author_id.toString());

    if (index >= 0) {
      item.author = authors[index];
    }
  });

  const str = readFileSync(join(__dirname, '/views/components/topics.ejs'), 'utf8');
  const suggestHtml = ejs.compile(str)({
    topics, title: '精华', zone: zone, appId: appId
  });

  return suggestHtml;
}
